import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import { fetchValidation } from '@/utils';
import {
  queryTakingList,
  queryTakingCount,
  operationQueset,
} from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    fetchCount: Effect;
    batchOperation: Effect;
  };
  reducers: {
    save: Reducer;
    cleanCount: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'logisCenterTaking',

  state: {
    data: {
      content: [],
      count: 0,
    },
    shelvesList: [],
    cabinetList: [],
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const { pageIndex, ...query } = payload.params;
      const response = yield call(queryTakingList, query);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: {
          type: 'list',
          value: {
            current: pageIndex,
            search: payload.search,
            list: data.body.list && data.body.list.map((item: any, index: number) => (
              { ...item, index: index + 1 }
            )),
            maxId: payload.maxId,
            minId: payload.minId,
          },
        },
      });
    },

    * fetchCount({ payload }, { call, put }) {
      const count = yield call(queryTakingCount, payload);
      yield put({
        type: 'save',
        payload: {
          type: 'count',
          value: count.body && count.body,
        },
      });
    },

    * batchOperation({
      payload: {
        search, params, maxId, minId, ...query
      },
    }, { call, put }) {
      const response = yield call(operationQueset, query);
      const data = fetchValidation(response);
      if (data) {
        message.success('操作成功');
        yield put({
          type: 'fetch',
          payload: { search, params },
        });
      }
    },
  },

  reducers: {
    save({ data }, { payload }) {
      if (payload.type === 'list') {
        const pos = data.content.findIndex((item: any) => item.current === payload.value.current);
        if (pos === -1) {
          data.content.push(payload.value);
        } else {
          data.content[pos] = payload.value;
        }
      } else if (payload.type === 'count') {
        data.count = payload.value;
      }
      return { data };
    },
    cleanCount({ data }) {
      data.count = 0;
      return { data };
    },
  },
};

export default Model;
